﻿/*
 * liu xing
 * 
 *  */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using JKF.Substructure;
using System.Data.Common;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace JKF.BusinessLayer
{
    /// <summary>
    /// 业务类的基类,
    /// 主要做sql语句的分页,
    /// 仿linq的方式
    /// </summary>
    public class BusinessBase
    {
        public BusinessBase()
            : this(SysConfig.PageSize)
        {

        }

        private const string _sessionClientIp = "__ClientIp";
        public static string  ClientIp
        {
            get
            {
                return SessionManager.Get(_sessionClientIp).ToString();
            }
            set
            {
                SessionManager.Set(_sessionClientIp, value);
            }
        }

        public BusinessBase(int pageSize)
        {
            this.PageSize = pageSize;
            this.DBHR = DB.HR;
        }

        private const string SqlCount = "select count(*) from ({0})";

        //private const string SqlPager = @"select * from (select * from ([Holder]) where rn <= {1} ) where rn >= {0}"; //oracle 写法
        //SELECT TOP 页大小 *  FROM  ( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table ) A WHERE RowNumber > 页大小*(页数-1)
        //private const string SqlPager = "SELECT TOP {页面大小} * FROM (([Holder]) A WHERE RowNumber >{当前第几页}*({页数}-1)";
        private const string SqlPager = "SELECT TOP {0} * FROM ([Holder]) A WHERE RowNumber >{0}*({1}-1)";
        protected int PageSize { get; set; }

        public Database DBHR { get; set; }

        /// <summary>
        /// 若有参数, 注意参数顺序,如果某个参数用了 2次,则按照循序传2次
        /// </summary>
        /// <param name="sqlText"></param>
        /// <param name="parameterValues"></param>
        /// <returns></returns>
        public int ExecCount(string sqlText, params object[] parameterValues)
        {
            var db = DBHR;
            //var ds = db.ExecuteDataSetSql(string.Format(SqlCount, sqlText), parameterValues);
            var dt= db.ExecuteDataSet(CommandType.Text, sqlText).Tables[0];
          
            return Convert.ToInt32(dt.Rows[0][0]);
        }

        /// <summary>
        /// 将普通的sql包装成,可分页的
        /// </summary>
        /// <param name="sqlText">必须有列 rownum rn,且不能用*</param>
        /// <param name="pageIndex"></param>
        /// <param name="parameterValues"></param>
        /// <returns></returns>
        //public DataTable ExecPager(string sqlText, int pageIndex, params object[] parameterValues)
        public DataTable ExecPager(string sqlText, int pageIndex)
        {
            var db = DBHR;
            StringBuilder sb = new StringBuilder();
            //sb.AppendFormat(SqlPager, pageIndex * PageSize - PageSize + 1, pageIndex * PageSize); //oracle写法
            sb.AppendFormat(SqlPager,PageSize, pageIndex);
            sb.Replace("[Holder]", sqlText);
            //return db.ExecuteDataSetSql(sb.ToString()).Tables[0];
            return db.ExecuteDataSet(CommandType.Text, sb.ToString()).Tables[0];
            //return db.ExecuteDataSetSql(sb.ToString(),null).Tables[0];
            
            
        }

        private DbCommand GetCommand(string sqlText, object[] vals)
        {
            var db = DBHR;
            var cmd = db.GetSqlStringCommand(sqlText);
            var i = 0;
            foreach (var v in vals)
            {
                if (v is Guid)
                {
                    db.AddInParameter(cmd, "p" + (i++).ToString(), DbType.Guid, v);
                    continue;
                }
                if (Regex.IsMatch(v.ToString(), "^[a-f0-9]{32}$", RegexOptions.IgnoreCase))
                {
                    db.AddInParameter(cmd, "p" + (i++).ToString(), DbType.Guid, StTool.GuidFromOraString(v.ToString()));
                    continue;
                }
                if (Regex.IsMatch(v.ToString(), "^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-fA-Z0-9]{12}$", RegexOptions.IgnoreCase))
                {
                    db.AddInParameter(cmd, "p" + (i++).ToString(), DbType.Guid, new Guid(v.ToString()));
                    continue;
                }
                if (v is ValueType) //各种数字类型
                {
                    db.AddInParameter(cmd, "p" + (i++).ToString(), DbType.Int32, v);
                    continue;
                }
                if (v is string)
                {
                    db.AddInParameter(cmd, "p" + (i++).ToString(), DbType.StringFixedLength, v.ToString());
                    continue;
                }
                throw new Exception("新改的分页,发现没有对应的参数类型,联系lxing 修改");

            }
            return cmd;
        }
    }
}
